package com.imflea.zero.service.user.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.imflea.zero.exception.BizException;
import com.imflea.zero.model.dao.user.WebUserAccountMapper;
import com.imflea.zero.model.entity.user.WebUserAccount;
import com.imflea.zero.model.entity.user.dto.WebUserAccountDto;
import com.imflea.zero.service.user.IWebUserAccountService;
import com.imflea.zero.util.base.CommonUtils;
import com.imflea.zero.utils.SessionUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 * 微信端用户账户 服务实现类
 * </p>
 *
 * @author zzz
 * @since 2024-02-22
 */
@Service
public class WebUserAccountServiceImpl extends ServiceImpl<WebUserAccountMapper, WebUserAccount> implements IWebUserAccountService {

    @Override
    public WebUserAccount saveOrUpdateWebUserAccount(WebUserAccount entity) {
        if (CommonUtils.isNull(entity.getId())) {
            entity.setId(CommonUtils.generateRandomString());
        }
        entity.setTenantId(SessionUtils.getTenantId());
        boolean b = this.saveOrUpdate(entity);
        if (!b) {
            throw new BizException("账户更新失败");
        }
        return entity;
    }

    @Override
    public PageInfo<WebUserAccount> queryPage(WebUserAccountDto dto) {
        Integer pageIndex = dto.getPageNum();
        Integer pageSize = dto.getPageSize();
        String tenantId = SessionUtils.getTenantId();
        QueryWrapper<WebUserAccount> queryWrapper = new QueryWrapper<>();
        if (!CommonUtils.isNull(tenantId)) {
            queryWrapper.eq("tenant_id", tenantId);
        }
        PageHelper.startPage(pageIndex, pageSize);
        List<WebUserAccount> adoptInfos = this.list(queryWrapper);
        PageInfo<WebUserAccount> pageResult = new PageInfo<>(adoptInfos);
        return pageResult;
    }

    @Override
    public WebUserAccount getAccountByUserId(String userId) {
        QueryWrapper<WebUserAccount> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        WebUserAccount account = this.getOne(queryWrapper);
        return account;
    }

    @Override
    public Boolean updateAountByUserId(String userId, BigDecimal semAmout) {
        UpdateWrapper<WebUserAccount> queryWrapper = new UpdateWrapper<>();
        queryWrapper.eq("user_id", userId);
        WebUserAccount account = this.getOne(queryWrapper);
        BigDecimal add = account.getUserAccount().add(semAmout);
        account.setUserAccount(add);
        boolean b = this.updateById(account);
        if (!b) {
            throw new BizException("更新用户账户余额失败！");
        }
        return b;
    }

}
